import { createResourceVerify } from '~/server/validation';
import { SubCategoryModel } from '~/server/models/sub_category.model';
import { MainCategoryModel } from '~/server/models/main_category.model';
import { IResource, ResourceModel } from '~/server/models/resource.model';

/**
 * @api {put} /admin/resource/create 创建资源
 * @apiName 创建资源
 * @apiGroup 资源管理
 * @apiDescription 创建资源
 *
 * @apiPermission admin、resource
 *
 * @apiSampleRequest /admin/resource/create
 *
 * @apiHeader {String} Authorization 用户 Token
 *
 * @apiBody {Object} resource 资源信息
 * @apiBody {String} resource.icon 图标
 * @apiBody {String} resource.name 名称
 * @apiBody {String} resource.description 描述
 * @apiBody {String} resource.url 链接
 * @apiBody {String} resource.details 详情
 * @apiBody {String} resource.mainCategoryId 主分类 ID
 * @apiBody {String} resource.subCategoryId 子分类 ID
 * @apiBody {Boolean} resource.isRecommend 是否推荐
 *
 * @apiSuccess {Number} code 响应状态码
 * @apiSuccess {String} message 响应消息
 * @apiSuccessExample {json} Success-Response:
 * HTTP/1.1 200 OK
 * {
 *   code: 1,
 *   message: '创建成功',
 * }
 */
export default defineEventHandler(async (event) => {
	const checkPermission = checkAdminUserPermission(event, ['admin', 'resource']);
	if (!checkPermission) {
		return {
			code: 0,
			message: '无权访问',
		};
	}

	try {
		const body = await readBody(event);

		const resource: IResource = body.resource;

		// 参数校验
		const validation: string | undefined = createResourceVerify.validate({ ...resource }).error
			?.message;
		if (validation && validation !== void 0) {
			return {
				code: 0,
				message: validation,
			};
		}

		// 查询资源是否已存在
		const resourceExists = await ResourceModel.findOne({ url: resource.url });
		if (resourceExists !== null) {
			return {
				code: 0,
				message: '资源已存在',
				resource: resourceExists,
			};
		}

		// 查询分类是否存在
		const mainCategoryExists = await MainCategoryModel.findById(resource.mainCategoryId);
		const subCategoryExists = await SubCategoryModel.findById(resource.subCategoryId);
		if (mainCategoryExists === null || subCategoryExists === null) {
			return {
				code: 0,
				message: '分类不存在',
			};
		}

		// 创建资源
		await ResourceModel.create({ ...resource });

		return {
			code: 1,
			message: '创建成功',
		};
	} catch (err: any) {
		error(err);
		return {
			code: 0,
			message: err.message,
		};
	}
});
